/**
 * @name zhangyy
 * @description zhangyy's code
 * Date: 2014/9/11
 * Time: 22:12
 *
 */
var request = require('request')
var utf8 = require('utf8')
var querystring = require("querystring")

Date.prototype.strftime = function (format) {
    var self = this;

    function padding(n, p) {
        if (n < 10) {
            return (p || '0') + n;
        }
        return n;
    }

    function repl(s, c) {
        switch (c) {
            case 'd':
                return padding(self.getDate());
            case 'e':
                return self.getDate();
            case 'u':
                return self.getDay() + 1;
            case 'w':
                return self.getDay();
            case 'm':
                return padding(self.getMonth() + 1);
            case 'C':
                return parseInt(self.getFullYear() / 20 - 1, 10);
            case 'y':
                return padding(self.getFullYear() % 100);
            case 'Y':
                return self.getFullYear();
            case 'H':
                return padding(self.getHours());
            case 'I':
                return padding(self.getHours() % 12);
            case 'l':
                return padding(self.getHours() % 12, ' ');
            case 'M':
                return padding(self.getMinutes());
            case 'p':
                return self.getHours() < 12 ? 'AM' : 'PM';
            case 'P':
                return self.getHours() < 12 ? 'am' : 'pm';
            case 'r':
                return self.strftime('%I:%M:%S %p');
            case 'R':
                return self.strftime('%H:%M');
            case 'S':
                return padding(self.getSeconds());
            case 'T':
                return self.strftime('%H:%M:%S');
            case 'D':
                return self.strftime('%m/%d/%Y');
            case 'F':
                return self.strftime('%Y-%m-%d');
            case 's':
                return parseInt(self.getTime() / 1000, 10);
            case 'x':
                return self.toLocaleDateString();
            case 'X':
                return self.toLocaleTimeString();
            case 'n':
                return '\n';
            case 't':
                return '\t';
            case '%':
                return '%';
            default:
                return self.strftime(c);
        }
        return c;
    }

    var ret = format.replace(/%(\w)/g, repl);
    return ret;
}

var utils = {
    extend: function (obj, obj1) {
        for (var key in obj1) {
            obj[key] = obj1[key]
        }
        return obj
    },

    paramOfUrl: function (url) {
        var paramSuit = url.substring(url.indexOf('?') + 1).split("&");
        var paramObj = {};
        for (var i = 0; i < paramSuit.length; i++) {
            var param = paramSuit[i].split('=');
            if (param.length == 2) {
                var key = decodeURIComponent(param[0]);
                var val = decodeURIComponent(param[1]);
                if (paramObj.hasOwnProperty(key)) {
                    if(!(paramObj[key] instanceof Array)){
                        paramObj[key] = [paramObj[key]]
                    }
                    paramObj[key].push(val);
                }
                else {
                    paramObj[key] = val;
                }
            }
        }
        return paramObj;
    },

    ajax: function (options) {
        var self = this
        var requestObj = utils.parseRequest(options.req)
        if (options.method) {
            requestObj.method = options.method
        }

        if (options.data) {
            requestObj.form = this.extend(requestObj.form, options.data)
        }

        requestObj.uri = options.fullUrl || (config.javaServer + options.url)
        requestObj.useQuerystring = true
        requestObj.proxyHeaderExclusiveList = {
            'content-encoding': 'utf-8'
        }
        for(var key in requestObj.form) {
            var value = requestObj.form[key]
            if(false && typeof value == 'string' && !options.notEncode){
                value = utf8.encode(requestObj.form[key])
            }
            requestObj.form[key] = value
        }

        if (requestObj.method.toLowerCase() == 'get') {
            requestObj.uri += '?' + querystring.stringify(requestObj.form)
            delete requestObj.form
        }
        //console.log('Request ' + (options.fullUrl || options.url) + ':' + JSON.stringify(requestObj))

        if(options.cookie){
            var j = request.jar()
            var cookie = request.cookie(options.cookie)
            j.setCookie(cookie, options.host, function (err, cookie){
                console.log('cookie err' + err + 'content:' + cookie)
            })
        }

        request(requestObj, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                //console.log('Response ' + (options.fullUrl || options.url) + ': ' + body)
                var result = {}
                try {
                    result = JSON.parse(body)
                } catch (e) {
                    result = {
                        code: '999',
                        message: '服务器忙晕了，请稍候刷新试试'
                    }
                }
                if (options.res) {
                    if (result.code != '200') {
                        self.goError(options.res, result.message)
                        return false
                    }
                }

                /*if (result.data) {
                 result.data = JSON.parse(result.data)
                 }*/
                options.callback && options.callback(result,body)
            } else {
                console.log('Response ' + options.url + ': ' + error)
                var result = {
                    code: '999',
                    message: '服务器忙晕了，请稍候刷新试试'
                }
                options.callback && options.callback(result, body)
            }
        })
    },

    parseRequest: function (req) {
        var param = {}

        if(!req) {
            return {
                form: {}
            }
        }

        console.log(req.body)

        if (JSON.stringify(req.query) != '{}') {
            param = this.extend(param, req.query)
        }
        if (JSON.stringify(req.body) != '{}') {
            param = this.extend(param, req.body)
        }

        delete param.service
        return {
            form: param,
            method: req.method,
            Cookie: req.headers.Cookie,
            sessionId: req.sessionID
        }
    }

};

module.exports = utils;